package com.glorysoft.hlgdpda.ui.login.viewmodel

import android.Manifest
import android.app.Activity
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import com.glorysoft.hlgdpda.base.BaseViewModel
import com.glorysoft.hlgdpda.base.Constant
import com.glorysoft.hlgdpda.base.MyApp
import com.glorysoft.hlgdpda.entity.LoginEntity
import com.glorysoft.hlgdpda.entity.ui.ToastMessageBean
import com.glorysoft.hlgdpda.model.LoginRepository
import com.google.gson.JsonObject
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.model.Response
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_DownloadFragmentDialog
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_VersionEntity
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_NetUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_SharePreferencesUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils
import pub.devrel.easypermissions.EasyPermissions
import java.util.*

/**
 * FileName: LoginViewModel
 * Author: XJH
 * Date: 2021/5/12 18:43
 * Description:
 * History:
 */
class LoginViewModel : BaseViewModel(){

    private val loginRepository = LoginRepository()
    var loginEntity = MutableLiveData<LoginEntity>()
    val PERMISSIONS_REQUEST_CODE = 10
    private var code = 0

    fun initUser(context: AppCompatActivity){
        loginEntity.value = LoginEntity();
        Constant.REQUEST_URL_DEBUG = FreeApi_SharePreferencesUtils.getSharePre("HLGD_FILE", "REQUEST_URL_DEBUG", Constant.REQUEST_URL_DEBUG, MyApp.app)
        Constant.FILE_URL = FreeApi_SharePreferencesUtils.getSharePre("HLGD_FILE", "FILE_URL_DEBUG", Constant.FILE_URL, MyApp.app)
        Constant.CURRENT_USER = FreeApi_SharePreferencesUtils.getSharePre("HLGD_FILE", "CURRENT_USER", MyApp.app)
        loginEntity.value?.USER?.USERNAME = Constant.CURRENT_USER
        Constant.AUTHORITYLIST.clear()
        requestPermission(context)
        detectionUpdate(context)

    }

    private fun requestPermission(context: Activity){
        //Manifest.permission.READ_PHONE_STATE 申请不到
        val perms = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
        //权限判断，第一次弹出系统的授权提示框
        if (EasyPermissions.hasPermissions(context, *perms)) {
            //@AfterPermissionGranted 有权限直接执行 todo...
            //login();
        } else {
            //没有权限的话，先提示，点确定后弹出系统的授权提示框
            EasyPermissions.requestPermissions(context, "程序运行需要权限",
                    PERMISSIONS_REQUEST_CODE, *perms)
        }
    }

    private fun detectionUpdate(context: AppCompatActivity) {
        val manager: PackageManager = context.packageManager
        var info: PackageInfo? = null
        try {
            info = manager.getPackageInfo(context.packageName, 0)
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        val version = info!!.versionName
        val callBack: FreeUI_EntityCallBack<FreeUI_VersionEntity> = object : FreeUI_EntityCallBack<FreeUI_VersionEntity>(object : TypeToken<FreeUI_VersionEntity?>() {}.type) {

            override fun onSuccess(response: Response<FreeUI_VersionEntity>) {
                val entity = response.body()
                entity.currentVersion = version
                val code = FreeApi_Utils.compareVersion(version, entity.version)
                if (code == -1) {
                    val downloadFragmentDialog = FreeUI_DownloadFragmentDialog()
                    downloadFragmentDialog.setData(entity)
                    downloadFragmentDialog.show(context.supportFragmentManager, "DOWNLOAD")
                }
            }
        }
        val map: Map<String, String> = HashMap()
        FreeApi_NetUtils.requestGetNet(Constant.FILE_URL, this, map, callBack)
    }

    fun login(){
        if (loginEntity.value!!.USER.USERNAME.isEmpty() || loginEntity.value!!.USER.PASSWORD.isEmpty()){
            defUI.toastEvent.value = ToastMessageBean("用户名或密码不能为空",false)
            return
        }

        val map = JsonObject()
        map.addProperty("ACTIONTYPE","LOGIN")
        map.addProperty("USERNAME",loginEntity.value!!.USER.USERNAME)
        map.addProperty("PASSWORD",loginEntity.value!!.USER.PASSWORD)
        launchOnlyResult({
            //登录请求
            loginRepository.getLogin(map)
            Constant.CURRENT_USER = loginEntity.value!!.USER.USERNAME
            val authorityMap = JsonObject()
            authorityMap.addProperty("NAME",loginEntity.value!!.USER.USERNAME)
            authorityMap.addProperty("AUTHORITYCATEGORY","PDA")
            //请求权限
            val authority = loginRepository.getAuthority(authorityMap)
            if (authority.AUTHORITYLIST.size > 0){
                defUI.toastEvent.value = ToastMessageBean("登录成功",true)
                authority.AUTHORITYLIST.forEach {
                    Constant.AUTHORITYLIST.add(it.LABELZH)
                }
                defUI.startActivity.call()
            }else{
                defUI.toastEvent.value = ToastMessageBean("当前登录人员无任何权限",false)
            }
        })

//        Constant.CURRENT_USER = loginEntity.value!!.USER.USERNAME
//        //请求权限
//        defUI.toastEvent.value = ToastMessageBean("登录成功",true)
//        defUI.startActivity.call()


    }
}